adc_esp = 0
import machine

print("\tESP ADC set to",end=' ')

if use.board:
    print('ADC pin is',end=' ')
    if machine.ADC(1).read()>65534:
        print("A0 (0)")
    else:
        print("VCC (1)")
        adc_esp = 1

#builtins.hspi = machine.SPI(1, baudrate=100000, polarity=0, phase=0)

# set up the SPI interface pins

class MCP3008:

    @ld
    def __init__(*a,**k):pass

    # 0/1 A0 pin of esp or VCC
    # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
    def readadc(self,adcnum, clock, mosi, miso, cs):
        if ((adcnum > 7) or (adcnum < 0)):
                return -1
        cs(1)
        clock(0)
        cs(0)

        commandout = adcnum
        commandout |= 0x18  # start bit + single-ended bit
        commandout <<= 3    # we only need to send 5 bits here
        for i in range(5):
                if (commandout & 0x80):
                        mosi(1)
                else:
                        mosi(0)
                commandout <<= 1
                clock(1)
                clock(0)

        adcout = 0
        # read in one empty bit, one null bit and 10 ADC bits
        for i in range(12):
                clock(1)
                clock(0)
                adcout <<= 1
                if ( miso.value()):
                    adcout |= 0x1

        cs(1)

        adcout /= 2       # first bit is 'null' so drop it
        return adcout

    # have A0-A7 behave like arduino , negative index will call ESP integrated adc
    def __call__(self,adcnum=-1):
        if adcnum<0:
            return self.adc0.read()
        return self.readadc(adcnum, self.clock, self.mosi, self.miso, self.cs )

#def tspi(chan=1):
#    cs= Pin('CS','w').hi()
#    Time.sleep(0.01)
#    hspi.write( b'\x01')
#    hspi.write( b'%s' % chr( (8+chan) <<4 ) )
#    hspi.write( b'\x00')
#    print( hspi.read(3) )


adc_esp = MCP3008(adc_esp)
export('ADC',adc_esp)
export('analogRead',adc_esp)

print('\t+ MCP3008')

#FIXME: use CD74HC4067 and digipots to feed ESP adc(0)
del MCP3008,adc_esp

